package com.xiaolin.sports.core.wechat.hander;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaolin.sports.common.enums.wechat.WechatEwmType;
import com.xiaolin.sports.model.ParentInfo;
import com.xiaolin.sports.model.SchoolInfo;
import com.xiaolin.sports.model.WechatSendMessage;
import com.xiaolin.sports.service.IChildSignInfoService;
import com.xiaolin.sports.service.IParentInfoService;
import com.xiaolin.sports.service.ISchoolInfoService;
import com.xiaolin.sports.service.IWechatMessageService;
import com.xiaolin.sports.service.IWechatSendService;
import com.xiaolin.sports.utils.DateUtil;
import com.xiaolin.sports.utils.PropertiesUtil;
import com.xiaolin.sports.utils.StringUtil;
import com.xiaolin.sports.utils.TextUtil;
import com.xiaolin.sports.wechat.common.Constants;
import com.xiaolin.sports.wechat.message.ArticleItem;
import com.xiaolin.sports.wechat.message.InputMessage;
import com.xiaolin.sports.wechat.message.OutputMessage;
import com.xiaolin.sports.wechat.model.WechatUserInfo;
import com.xiaolin.sports.wechat.utils.MessageUtil;
import com.xiaolin.sports.wechat.utils.WechatUtils;

@Component
public class WechatHander {
	
	@Autowired
	private IWechatSendService wechatSendService;
	@Autowired
	private IWechatMessageService wechatMessageService;
	@Autowired
	private IChildSignInfoService childSignInfoService;
	@Autowired
	private IParentInfoService parentInfoService;
	@Autowired
	private ISchoolInfoService schoolInfoService;

	public OutputMessage respMessage(InputMessage inputMsg) throws Exception{
		String servername = inputMsg.getToUserName();// 服务端  
        String custermname = inputMsg.getFromUserName();// 客户端  
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间  
        
        // 取得消息类型  
        String msgType = inputMsg.getMsgType();  
        OutputMessage outputMsg = new OutputMessage();  
        outputMsg.setFromUserName(servername);  
        outputMsg.setToUserName(custermname);  
        outputMsg.setCreateTime(returnTime);  
        String respContent = null;
        // 根据消息类型获取对应的消息内容  
        if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {  
        	reqMessageTypeTextOutput(outputMsg, inputMsg);
        } // 获取并返回多图片消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
        	
        }// 视频消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_SHORTVIDEO) || msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
			
		}
		else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {// 语音消息
			
		}// 地理位置消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
			
		}// 链接消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
			
		}
		else {
    		// 事件推送
    		if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
    			// 事件类型
    			String eventType = inputMsg.getEvent();
    			// 关注
    			if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
    				String eventKey = inputMsg.getEventKey();
    				if(eventKey != null && eventKey.indexOf("qrscene_") != -1) {
    					eventKey = eventKey.replaceAll("qrscene_", "");
    					eventTypeScanOutPut(outputMsg, eventKey, inputMsg.getFromUserName());
    				}
    			}
    			// 取消关注
    			else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
    				// TODO 取消订阅后用户不会再收到公众账号发送的消息，因此不需要回复
    			}
    			// 扫描带参数二维码
    			else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
    				String eventKey = inputMsg.getEventKey();
    				eventTypeScanOutPut(outputMsg, eventKey, inputMsg.getFromUserName());
    			}
    			// 上报地理位置
    			else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {
    				// TODO 处理上报地理位置事件
    			}
    			// 自定义菜单
    			else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
    				eventTypeClick(outputMsg, inputMsg);
    			}
    		}else {
    			outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
                outputMsg.setContent(respContent);
    		}
		}
        return outputMsg;
	}
	
	
	/**
	 * 文本消息响应
	 * @auther 胡启萌
	 * @Date 2016年12月4日
	 * @param outputMsg
	 * @param inputMsg
	 */
	private void reqMessageTypeTextOutput(OutputMessage outputMsg, InputMessage inputMsg) {
		List<WechatSendMessage> list = wechatSendService.selectListByParams(inputMsg.getContent());
		if(!StringUtil.isNullOrEmpty(list)) {
			if(MessageUtil.RESP_MESSAGE_TYPE_NEWS.equals(list.get(0).getMsgtype())) {
				outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
				List<ArticleItem> newsList = new ArrayList<>();
				for(WechatSendMessage message : list) {
	    			ArticleItem item = new ArticleItem();
	    	        item.setTitle(message.getTitle());
	    	        item.setDescription(message.getDescription());
	    	        item.setPicUrl(message.getPicurl());
	    	        item.setUrl(message.getUrl());
	    	        newsList.add(item);
				}
				outputMsg.setArticleCount(newsList.size());
				outputMsg.setArticles(newsList);
			}
		}else {
			if(inputMsg.getContent().equals("客服")) {
				customerService(outputMsg);
			}else {
				outputMsg.setContent("欢迎光临小林体育LAM公众号");
		        outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			}
		}
	}
	
	/**
	 * 扫描带参数二维码响应
	 * @auther 胡启萌
	 * @Date 2016年12月4日
	 * @param outputMsg
	 * @param eventKey
	 * @param openid
	 */
	private void eventTypeScanOutPut(OutputMessage outputMsg, String eventKey, String openid) {
		int type = Integer.parseInt(eventKey.substring(0, 1)); 
		String key = eventKey.substring(1, eventKey.length());
		String content = null;
		if(WechatEwmType.POSTER.getCode() == type) {
			Integer schoolId = Integer.valueOf(key);
			SchoolInfo schoolInfo = schoolInfoService.selectById(schoolId);
			ParentInfo parentInfo = parentInfoService.selectByOpenid(openid);
			if(parentInfo != null && parentInfo.getSchoolId() != null) {
				String template = PropertiesUtil.getProperty("bind_school_had");
				String[] strings = new String[]{schoolInfo.getSchoolName(), 
						DateUtil.dateToStr(parentInfo.getBindTime(), DateUtil.DEFAULT_DATE_FORMAT),
						Constants.BASEPATH + "/course"};
				content = TextUtil.format(template, strings);
			}else {
				if(parentInfo == null) {
					parentInfo = new ParentInfo();
					WechatUserInfo userInfo = WechatUtils.getUserInfo(WechatUtils.getWechatModel().getAccessToken(), openid);
					parentInfo.setHeadImg(userInfo.getHeadimgurl());
					parentInfo.setCity(userInfo.getCity());
					parentInfo.setProvince(userInfo.getProvince());
					parentInfo.setNickName(userInfo.getNickname());
					parentInfo.setOpenid(userInfo.getOpenid());
				}
				parentInfo.setBindTime(new Date());
				parentInfo.setSchoolId(schoolId);
				parentInfo.setSchoolName(schoolInfo.getSchoolName());
				parentInfoService.addAndUpdate(parentInfo);
				String template = PropertiesUtil.getProperty("bind_school_success");
				String[] strings = new String[]{schoolInfo.getSchoolName(), 
						DateUtil.dateToStr(parentInfo.getBindTime(), DateUtil.DEFAULT_DATE_FORMAT),
						Constants.BASEPATH + "/user/account"};
				content = TextUtil.format(template, strings);
			}
			
		}
		if(StringUtils.isNotBlank(content)) {
			outputMsg.setContent(content);
			outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		}
	}
	
	private void eventTypeClick(OutputMessage outputMsg, InputMessage inputMsg) {
//		if(inputMsg.getEventKey().equals("rselfmenu_3_0")) {
//			List<ArticleItem> newsList = WechatUtils.getMaterialMediaList(NewsTypeEnum.NEWS_INFO.getCode());
//			outputMsg.setArticleCount(newsList.size());
//			outputMsg.setArticles(newsList);
//			outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
//		}else if(inputMsg.getEventKey().equals("rselfmenu_3_1")) {
//			List<ArticleItem> newsList = WechatUtils.getMaterialMediaList(NewsTypeEnum.SCHOOL_CASE.getCode());
//			outputMsg.setArticleCount(newsList.size());
//			outputMsg.setArticles(newsList);
//			outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
//		}else if(inputMsg.getEventKey().equals("rselfmenu_3_2")) {
//			List<ArticleItem> newsList = WechatUtils.getMaterialMediaList(NewsType.ABOUT_US.getCode());
//			outputMsg.setArticleCount(newsList.size());
//			outputMsg.setArticles(newsList);
//			outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
//		}else if(inputMsg.getEventKey().equals(MessageUtil.RESP_TRANSFER_CUSTOMER_SERVICE)) {
//			customerService(outputMsg);
//		}
	}
		
	@SuppressWarnings("deprecation")
	private void customerService(OutputMessage outputMsg) {
		 Date now = new Date();
		 int hours = now.getHours();
         if(!(hours >= 9 && hours < 18)) {
        	 outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
        	 outputMsg.setContent("非常抱歉，我们的客服工作时间是：09:00-18:00！谢谢谢您的理解");
         }else {
        	 outputMsg.setMsgType(MessageUtil.RESP_TRANSFER_CUSTOMER_SERVICE); 
         }
	}
	
}
